<?php

class Notification extends CActiveRecord
{
	const NOTIFY_REGISTRATION = 1;
	const NOTIFY_REGISTRATION_ADMIN = 2;
	
//	private $_params = array(
//		'sitename' => '',
//		'username' => '',
//	);
//	
//	public function init()
//	{
//		$this->_params['sitename'] = Yii::app()->name;
//	}
//
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{notification}}';
	}

	public function rules()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$required = '';
		foreach ($languages as $lang)
		{
			$required .= 'subject_'.$lang.', body_'.$lang.',';
		}
		$required = trim($required, ',');
		$length = '';
		foreach ($languages as $lang)
		{
			$length .= 'subject_'.$lang.', body_'.$lang.',';
		}
		$length = trim($length, ',');
		return array(
			array($required, 'required'),
			array($length, 'length', 'max'=>255),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, creation_date', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		$languages = Languages::model()->getLanguageCodes();
		
		$labels = array(
			'id' => tt('ID'),
			'creation_date' => tt('Creation Date'),
		);
		foreach($languages as $lang)
		{
			$labels['subject_'.$lang] = tt('Subject');
			$labels['body_'.$lang] = tt('Body');
		}
		
		return $labels;
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$languages = Languages::model()->getLanguageCodes();
		foreach ($languages as $lang)
		{
			$criteria->compare('subject_'.$lang,$this->{'subject_'.$lang},true);
			$criteria->compare('body_'.$lang,$this->{'body_'.$lang},true);
		}
		$criteria->compare('id',$this->id);
		$criteria->compare('creation_date',$this->creation_date,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
	
	public function behaviors(){
		return array(
			'AutoTimestampBehavior' => array(
				'class' => 'zii.behaviors.CTimestampBehavior',
				'createAttribute' => 'creation_date',
				'updateAttribute' => null,
			),
		);
	}

	public function send($id, $emailFrom, $emailTo, $params)
	{
		$notification = $this->findByPk($id);
		Yii::app()->mailer->AddAddress($emailTo);
		Yii::app()->mailer->Subject = $notification->{'subject_'.Yii::app()->language};
		Yii::app()->mailer->From = $emailFrom;
		$body = $notification->{'body_'.Yii::app()->language};
		foreach ($params as $key=>$value)
		{
			$body = str_replace("%{$key}%", $value, $body);
		}
		Yii::app()->mailer->MsgHTML($body);
		Yii::app()->mailer->Send();
		
	}
}